<template>
  <div class="main-container">
    <div class="sidebar" :class="{'green-theme': diseaseData.code === 'N'}" v-if="!isLoading">
      <div class="sidebar-content">
        <!-- 动态疾病概览 -->
        <div class="disease-summary">
          <div class="disease-header">
            <h3>{{ diseaseData.name }}</h3>
            <div class="probability-tag">{{ diseaseData.probability }} 可能性</div>
          </div>
          <div class="risk-level" :class="diseaseData.riskClass">
            <i class="icon-warning"></i>
            <span>{{ diseaseData.riskText }}</span>
          </div>
        </div>

        <!-- 动态关键指标 -->
        <div class="key-indicators">
          <h4>异常指标 <span class="tip">(点击查看建议)</span></h4>
          <div class="indicator-list">
            <div
              v-for="(indicator, index) in diseaseData.indicators"
              :key="index"
              class="indicator-item"
              @click="insertText(indicator.question)"
            >
              <div class="indicator-label">{{ indicator.label }}</div>
              <div class="indicator-value">
                {{ indicator.value }}
                <span class="ref-range" :class="{ abnormal: indicator.abnormal }">
                  ({{ indicator.refRange }})
                </span>
              </div>
            </div>
          </div>
        </div>

        <!-- 动态治疗建议 -->
        <div class="treatment-recommendations">
          <h4>推荐方案</h4>
          <div
            v-for="(recommendation, index) in diseaseData.recommendations"
            :key="index"
            class="recommendation-block"
            @click="insertText(recommendation.question)"
          >
            <div class="recommendation-icon">{{ recommendation.icon }}</div>
            <div class="recommendation-content">
              <div class="title">{{ recommendation.title }}</div>
              <div class="desc">{{ recommendation.desc }}</div>
            </div>
          </div>
        </div>

        <!-- 动态预防建议 -->
        <div class="prevention-tips">
          <h4>护眼建议</h4>
          <div
            v-for="(tip, index) in diseaseData.preventions"
            :key="index"
            class="tip-item"
            @click="insertText(tip.question)"
          >
            ✅ {{ tip.text }}
          </div>
        </div>
      </div>
    </div>
    <div v-if="isLoading" class="loading-overlay">
      <div class="loading-spinner"></div>
      <p>正在分析眼部数据...</p>
    </div>
    <div class="chat-wrapper">
      <div class="chat-container">
        <!-- 消息区域 -->
        <div ref="messageContainer" class="messages">
          <div
            v-for="(message, index) in messages"
            :key="index"
            :class="['message', message.role]"
          >
            <div class="content" v-html="message.content"></div>
          </div>
          <div v-if="loading" class="loading">AI正在思考中...</div>
        </div>

        <!-- 输入区域 -->
        <div class="input-area">
          <textarea
            v-model="inputText"
            @keydown.enter.exact.prevent="sendMessage"
            placeholder="输入你的问题..."
            rows="1"
            ref="textarea"
          ></textarea>
          <button @click="sendMessage" :disabled="loading">
            <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
              <path fill="currentColor" d="M3 20v-6l8-2l-8-2V4l19 8z"/>
            </svg>
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, nextTick,computed ,onMounted } from 'vue'
import {useRoute} from "vue-router";
import DOMPurify from 'dompurify';
import {request} from "/src/utils/service";
// 消息数据
const messages = ref([])
const inputText = ref('')
const loading = ref(false)
const messageContainer = ref(null)
const textarea = ref(null)
const route=useRoute();
const thisId = route.query.Id; // 通过 query 获取参数
const dynamicProbability = ref(null)
const isLoading = ref(true); // 新增加载状态
const diseaseConfig = {
  0: { // 正常
    code: 'N',
    name: '正常眼部',
    riskClass: 'normal-status',
    riskText: '健康状态',
    indicators: [
      { label: '裸眼视力', value: '1.2 / 1.0', refRange: '正常 ≥1.0', abnormal: false, question: '如何保持良好视力？' },
      { label: '眼压', value: '16mmHg', refRange: '正常 10-21', abnormal: false, question: '日常如何维护正常眼压？' }
    ],
    recommendations: [
      { icon: '👀', title: '视力保养', desc: '定期眼部检查', question: '建议多久检查一次眼睛？' }
    ],
    preventions: [
      { text: '20-20-20用眼法则', question: '什么是正确的用眼习惯？' },
      { text: '补充叶黄素', question: '哪些食物富含护眼营养素？' },
      { text: '防蓝光措施', question: '电子屏幕如何保护眼睛？' }
    ]
  },
  1: { // 糖尿病视网膜病变
    code: 'D',
    name: '糖尿病视网膜病变',
    riskClass: 'high-risk',
    riskText: '高风险需干预',
    indicators: [
      { label: '微血管瘤', value: '阳性', refRange: '正常：阴性', abnormal: true, question: '微血管瘤阳性需要立即治疗吗？' },
      { label: '血糖值', value: '8.6mmol/L', refRange: '正常 ≤6.1', abnormal: true, question: '血糖控制目标是多少？' },
      { label: '黄斑水肿', value: '存在', refRange: '正常：无', abnormal: true, question: '黄斑水肿如何治疗？' }
    ],
    recommendations: [
      { icon: '💉', title: '胰岛素治疗', desc: '控制血糖水平', question: '胰岛素治疗的注意事项？' },
      { icon: '🩺', title: '眼底激光', desc: '防止新生血管形成', question: '激光治疗会有副作用吗？' }
    ],
    preventions: [
      { text: '严格控糖饮食', question: '糖尿病饮食建议？' },
      { text: '季度眼底检查', question: '糖尿病患者检查频率？' },
      { text: '控制血压血脂', question: '三高如何相互影响？' }
    ]
  },
  2: { // 青光眼
    code: 'G',
    name: '青光眼',
    riskClass: 'high-risk',
    riskText: '高风险需紧急处理',
    indicators: [
      { label: '眼压', value: '28mmHg', refRange: '正常 10-21', abnormal: true, question: '眼压过高如何处理？' },
      { label: '杯盘比', value: '0.8', refRange: '正常 ≤0.6', abnormal: true, question: '杯盘比增大意味着什么？' },
      { label: '视野缺损', value: '鼻侧象限', refRange: '正常：完整', abnormal: true, question: '视野能恢复吗？' }
    ],
    recommendations: [
      { icon: '💧', title: '降眼压治疗', desc: '药物控制眼压', question: '降眼压药物的副作用？' },
      { icon: '⚡', title: '激光手术', desc: '小梁成形术', question: '手术成功率有多少？' }
    ],
    preventions: [
      { text: '避免暗环境用眼', question: '青光眼日常注意事项？' },
      { text: '控制情绪波动', question: '情绪如何影响眼压？' },
      { text: '禁用散瞳药物', question: '哪些药物需要避免？' }
    ]
  },
  3: { // 白内障
    code: 'C',
    name: '白内障',
    riskClass: 'high-risk',
    riskText: '高风险需干预',
    indicators: [
      { label: '矫正视力', value: '0.6 / 0.5', refRange: '参考 ≥1.0', abnormal: true, question: '我的矫正视力低于正常值，需要手术吗？' },
      { label: '晶状体混浊', value: 'III级核性', refRange: '正常：透明', abnormal: true, question: '晶状体混浊III级有多严重？' }
    ],
    recommendations: [
      { icon: '👁️', title: '超声乳化手术', desc: '首选治疗方案，创伤小恢复快', question: '超声乳化手术的恢复期需要多久？' },
      { icon: '🔍', title: '晶体植入', desc: '根据生物测量数据定制', question: '人工晶体如何选择？' }
    ],
    preventions: [
      { text: '佩戴防紫外线眼镜', question: '如何预防白内障发展？' },
      { text: '补充维生素C/E', question: '饮食需要注意什么？' },
      { text: '控制糖尿病', question: '血糖与白内障的关系？' }
    ]
  },
  4: { // AMD
    code: 'A',
    name: '黄斑变性',
    riskClass: 'medium-risk',
    riskText: '需定期随访',
    indicators: [
      { label: '中心视力', value: '0.3', refRange: '正常 ≥0.8', abnormal: true, question: '中心视力丧失能恢复吗？' },
      { label: '黄斑区', value: '地图样萎缩', refRange: '正常：平整', abnormal: true, question: '干性AMD如何治疗？' }
    ],
    recommendations: [
      { icon: '💊', title: '抗VEGF治疗', desc: '玻璃体注射给药', question: '注射治疗需要多久一次？' },
      { icon: '🛡️', title: '抗氧化剂', desc: '补充锌和叶黄素', question: '推荐剂量是多少？' }
    ],
    preventions: [
      { text: '戒烟', question: '吸烟如何影响AMD？' },
      { text: '佩戴防蓝光眼镜', question: '电子设备使用建议？' },
      { text: '定期自测Amsler表', question: '如何自我监测病情？' }
    ]
  },
  5: { // 高血压
    code: 'H',
    name: '高血压视网膜病变',
    riskClass: 'high-risk',
    riskText: '需全身管理',
    indicators: [
      { label: '血压值', value: '165/100mmHg', refRange: '正常 <140/90', abnormal: true, question: '高血压急症如何处理？' },
      { label: '动脉狭窄', value: 'II级', refRange: '正常：无狭窄', abnormal: true, question: '动脉狭窄分级标准？' }
    ],
    recommendations: [
      { icon: '❤️', title: '降压治疗', desc: '联合用药控制血压', question: '理想血压值是多少？' },
      { icon: '🩸', title: '血脂管理', desc: '他汀类药物应用', question: '降脂药需要长期服用吗？' }
    ],
    preventions: [
      { text: '低盐饮食', question: '每日钠摄入标准？' },
      { text: '动态血压监测', question: '家庭血压测量方法？' },
      { text: '控制体重', question: 'BMI目标值是多少？' }
    ]
  },
  6: { // 近视
    code: 'M',
    name: '病理性近视',
    riskClass: 'medium-risk',
    riskText: '需控制发展',
    indicators: [
      { label: '屈光度', value: '-8.50D', refRange: '正常 ≥-6.00D', abnormal: true, question: '高度近视有哪些风险？' },
      { label: '眼轴长度', value: '28.6mm', refRange: '正常 ≤26mm', abnormal: true, question: '眼轴过长如何控制？' }
    ],
    recommendations: [
      { icon: '👓', title: '屈光矫正', desc: 'RGP/角膜塑形镜', question: '哪种矫正方式更好？' },
      { icon: '⚡', title: '后巩膜加固术', desc: '控制眼轴增长', question: '手术风险大吗？' }
    ],
    preventions: [
      { text: '增加户外活动', question: '每天需要多久户外？' },
      { text: '正确用眼姿势', question: '读写距离怎么控制？' },
      { text: '避免眼轴检查', question: '多久检测一次眼轴？' }
    ]
  },
  7: { // 其他
    code: 'O',
    name: '其他基本/异常',
    riskClass: 'medium-risk',
    riskText: '需进一步检查',
    indicators: [
      { label: '眼前节', value: 'KP(+)', refRange: '正常：阴性', abnormal: true, question: '角膜后沉积物是什么？' },
      { label: '玻璃体', value: '混浊++', refRange: '正常：透明', abnormal: true, question: '飞蚊症需要治疗吗？' }
    ],
    recommendations: [
      { icon: '🔬', title: '专科会诊', desc: '角膜病/葡萄膜炎专家', question: '推荐哪个专科医生？' },
      { icon: '🩺', title: '进一步检查', desc: 'OCT/UBM检查', question: '这些检查有什么作用？' }
    ],
    preventions: [
      { text: '避免揉眼', question: '眼部卫生注意事项？' },
      { text: '记录症状变化', question: '哪些症状需要警惕？' },
      { text: '定期复查', question: '建议复查频率？' }
    ]
  }
}
const getEyeDiseaseType = async () => {
  try {
    // 第一步：获取图像信息
    const imageResponse = await request({
      url: `/api/images/${thisId}/get_one`,
      method: 'get'
    });

    // 从URL中提取结果ID
    const resultId = parseInt(imageResponse.data.image_url.match(/(\d+)_left/)[1]);

    // 处理路径格式
    const targetPath = imageResponse.data.image_url.replace(/\\[^\\]+$/, '');
    const localFilePath = targetPath.replace(/\//g, '\\');

    // 第二步：获取诊断结果
    const postData = new FormData();
    postData.append('image_url', localFilePath);

    const resultResponse = await request({
      url: `/api/images/${resultId}/get_result/`,
      method: 'post',
      data: postData,
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });

    // 定义疾病类型及其对应的键
    const diseaseKeys = ['N', 'D', 'G', 'C', 'A', 'H', 'M', 'O'];
    const diseaseData = diseaseKeys.map(key => resultResponse.data[key] || 0);

    // 找到最大值对应的索引和值
    const maxValue = Math.max(...diseaseData);
    const maxIndex = diseaseData.indexOf(maxValue);

    // 返回两个值：最大概率值和疾病索引
    return { probability: maxValue, index: maxIndex };

  } catch (error) {
    console.error('Error in getEyeDiseaseType:', error);
    throw error; // 或者返回默认值：return { probability: 0, index: 0 };
  }
};

const diseaseTypeIndex = ref(0); // 默认值（比如3代表白内障）
const diseaseData = computed(() => {
  const config = diseaseConfig[diseaseTypeIndex.value];
  return {
    ...config,
    probability: dynamicProbability.value !== null
      ? `${(dynamicProbability.value * 100).toFixed(2)}%`
      : '--%'
  };
});
async function updateDiseaseData() {
  try {
    isLoading.value = true; // 开始加载
    const { probability, index } = await getEyeDiseaseType();
    dynamicProbability.value = probability;
    diseaseTypeIndex.value = index;
  } catch (error) {
    console.error('更新疾病数据失败:', error);
    // 失败时使用默认值
    diseaseTypeIndex.value = 0;
    dynamicProbability.value = null;
  } finally {
    isLoading.value = false; // 无论成功失败都结束加载
  }
}
onMounted(() => {
  updateDiseaseData();
});
const insertText = (question) => {
  inputText.value = question;  // 将问题填入输入框
  adjustHeight();              // 调整输入框高度
  nextTick(() => {
    textarea.value.focus();    // 自动聚焦到输入框
    scrollToBottom();          // 确保输入框可见
  });
};
// 自动调整输入框高度
const adjustHeight = () => {
  textarea.value.style.height = 'auto'
  textarea.value.style.height = textarea.value.scrollHeight + 'px'
}

// 发送消息
const sendMessage = async () => {
  if (!inputText.value.trim() || loading.value) return;

  const userInput = inputText.value.trim();
  messages.value.push({ role: 'user', content: userInput });
  inputText.value = '';
  adjustHeight();

  try {
    loading.value = true;
    scrollToBottom();

    const response = await fetch('/deepseek/v1/chat/completions', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${import.meta.env.VITE_DEEPSEEK_KEY}`
      },
      body: JSON.stringify({
        model: "deepseek-chat",
        messages: [{ role: "user", content: userInput }],
        temperature: 0.5
      })
    });

    if (!response.ok) throw new Error(`HTTP错误 ${response.status}`);

    const data = await response.json();
    const rawContent = data.choices[0].message.content;

    // 结构化处理消息内容
    const formattedContent = DOMPurify.sanitize(
      rawContent
        // 标题处理
        .replace(/###+\s(.+)/g, '<h3 class="section-title">$1</h3>')
        // 列表项处理
        .replace(/-\s(.+)/g, '<li class="list-item">$1</li>')
        // 加粗强调
        .replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>')
        // 段落换行
        .replace(/\n/g, '<br>')
    );
    messages.value.push({
      role: 'assistant',
      content: formattedContent
    });

  } catch (error) {
    console.error('请求失败:', error);
    messages.value.push({
      role: 'assistant',
      content: `服务暂时不可用，错误信息: ${error.message}`
    });
  } finally {
    loading.value = false;
    scrollToBottom();
  }
};

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (messageContainer.value) {
      messageContainer.value.scrollTop = messageContainer.value.scrollHeight
    }
  })
}

// 初始欢迎消息
messages.value.push({
  role: 'assistant',
  content: '你好！我是AI助手，有什么可以帮您的？'
})
</script>

<style scoped>
.main-container {
  display: flex;
  height: 100vh;
  background: #f5f7fb;
}

.chat-wrapper {
   flex: 1;
  height: 100vh;
  padding: 24px;
  background: #f5f7fb;
}
.message.assistant .content {
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
  line-height: 1.6;
  color: #333;
}

/* 标题样式 */
.section-title {
  font-size: 1.1em;
  color: #2a6df5;
  margin: 15px 0 10px;
  padding-bottom: 5px;
  border-bottom: 1px solid #eee;
}

/* 列表项样式 */
.list-item {
  position: relative;
  padding-left: 1.2em;
  margin: 8px 0;
}

.list-item::before {
  content: "•";
  color: #2a6df5;
  position: absolute;
  left: 0;
}

/* 强调文本 */
strong {
  color: #cc0000;
  font-weight: 600;
}

/* 移动端适配 */
@media (max-width: 480px) {
  .section-title {
    font-size: 1em;
  }

  .list-item {
    font-size: 14px;
  }
}
.chat-container {
  height: 100%;
  margin: 0 auto;
  max-width: 800px;
  display: flex;
  flex-direction: column;
  background: white;
  border-radius: 12px;
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.06);
}

.messages {
  flex: 1;
  padding: 24px;
  overflow-y: auto;
  scroll-behavior: smooth;
}

.message {
  margin: 16px 0;
  display: flex;
}

.message.user {
  justify-content: flex-end;
}

.message .content {
  max-width: 75%;
  padding: 12px 16px;
  line-height: 1.6;
  font-size: 15px;
}

.message.user .content {
  background: #2a6df5;
  color: white;
  border-radius: 12px 12px 4px 12px;
}

.message.assistant .content {
  background: #f7f7f8;
  color: #333;
  border-radius: 12px 12px 12px 4px;
}

.input-area {
  display: flex;
  gap: 12px;
  padding: 20px;
  border-top: 1px solid rgba(0, 0, 0, 0.06);
}

textarea {
  flex: 1;
  padding: 12px 16px;
  border: 1px solid rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  resize: none;
  max-height: 150px;
  font-size: 15px;
  line-height: 1.6;
  transition: all 0.2s;
  overflow: hidden;
}

textarea:focus {
  outline: none;
  border-color: #2a6df5;
  box-shadow: 0 0 0 3px rgba(42, 109, 245, 0.1);
}

button {
  width: 48px;
  height: 48px;
  border: none;
  background: #2a6df5;
  color: white;
  border-radius: 8px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background 0.2s;
}

button:disabled {
  background: #a0b4e0;
  cursor: not-allowed;
}

.loading {
  color: rgba(0, 0, 0, 0.4);
  padding: 16px;
  text-align: center;
  font-size: 14px;
}

@media (max-width: 768px) {
  .chat-wrapper {
    padding: 12px;
  }

  .message .content {
    max-width: 85%;
  }
}
.sidebar {
  width: 320px;
  background: #f8fafc;
  border-right: 1px solid #e0e0e0;
  padding: 20px;
}

.sidebar-content > div {
  margin-bottom: 25px;
}

/* 疾病概览 */
.disease-summary {
  background: white;
  padding: 15px;
  border-radius: 10px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.05);
}

.disease-header {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.disease-header h3 {
  margin: 0;
  font-size: 18px;
  color: #2c3e50;
}

.probability-tag {
  margin-left: auto;
  background: #ffebee;
  color: #cc0000;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.risk-level {
  display: flex;
  align-items: center;
  padding: 8px;
  border-radius: 4px;
  font-size: 13px;
}

.risk-level.high-risk {
  background: #fff0f0;
  color: #cc0000;
}

.icon-warning {
  display: inline-block;
  width: 16px;
  height: 16px;
  background: #cc0000;
  border-radius: 50%;
  margin-right: 8px;
}

/* 指标列表 */
.key-indicators h4 {
  color: #444;
  font-size: 15px;
  margin: 15px 0 10px;
}

.tip {
  font-size: 12px;
  color: #999;
}

.indicator-list {
  background: white;
  border-radius: 8px;
  overflow: hidden;
}

.indicator-item {
  padding: 12px;
  border-bottom: 1px solid #eee;
  cursor: pointer;
  transition: all 0.2s;
}

.indicator-item:hover {
  background: #e3f2fd;
}

.indicator-label {
  font-size: 13px;
  color: #666;
  margin-bottom: 4px;
}

.indicator-value {
  font-weight: 500;
  color: #2c3e50;
}

.ref-range {
  font-size: 12px;
  margin-left: 8px;
}

.ref-range.abnormal {
  color: #cc0000;
  font-weight: bold;
}

/* 治疗建议 */
.recommendation-block {
  display: flex;
  align-items: center;
  padding: 12px;
  background: white;
  border-radius: 8px;
  margin: 8px 0;
  cursor: pointer;
  transition: transform 0.2s;
}

.recommendation-block:hover {
  transform: translateX(4px);
}

.recommendation-icon {
  font-size: 24px;
  margin-right: 12px;
}

.recommendation-content .title {
  font-weight: 500;
  color: #2c3e50;
}

.recommendation-content .desc {
  font-size: 12px;
  color: #666;
}

/* 预防建议 */
.tip-item {
  padding: 10px;
  background: white;
  border-radius: 6px;
  margin: 6px 0;
  cursor: pointer;
  transition: all 0.2s;
}

.tip-item:hover {
  box-shadow: 0 2px 6px rgba(0,0,0,0.05);
}
.risk-level {
  display: flex;
  align-items: center;
  padding: 8px;
  border-radius: 4px;
  font-size: 13px;
}
.sidebar.green-theme {
  background: #f4fbf2;
  border-color: #7bc67b;
}

.green-theme .disease-summary {
  background: linear-gradient(145deg, #f0fff0, #e0f7e0);
  border: 1px solid #7bc67b;
}

.green-theme .probability-tag {
  background: #4caf50 !important;
  color: white;
}

.green-theme .risk-level {
  background: #e8f5e9;
  color: #2e7d32;
}

.green-theme .risk-level i {
  background: #4caf50;
}

.green-theme .key-indicators h4 {
  color: #388e3c;
}

.green-theme .indicator-item:hover {
  background: #e8f5e9;
}

.green-theme .recommendation-block:hover {
  box-shadow: 0 2px 8px rgba(76, 175, 80, 0.15);
}

.green-theme .tip-item:hover {
  background: #e8f5e9;
}
.normal { background: #e8f4ff; color: #0066cc; }
.medium-risk { background: #fff3e0; color: #ff6d00; }
.high-risk { background: #ffebee; color: #cc0000; }
</style>